import { ref, reactive } from 'vue'
import app from '@/app'
import math from '@/app/math'
import checkoutModel from '@/model/account/checkout'
import accountModel from '@/model/account'
import printerModel from '@/model/printer'

import { total } from '@/api/store/order'
import { totalGroup } from '@/api/store/order_pay'

// 加载时间数据 
const timeBuild = (name, uint, add = 0, count = 0) => {
  return app.time.splitStartEnd(app.time.startEnd(name, add), count, uint).map(item => [item[0].unix(), item[1].unix()])
}

const timeData = [
  timeBuild('day', 'hour', 0, 1),
  timeBuild('day', 'hour', -1, 1),
  timeBuild('week', 'day'),
  timeBuild('week', 'day', -1),
  timeBuild('month', 'day'),
  timeBuild('month', 'day', -1),
  timeBuild('quarter', 'month'),
  timeBuild('quarter', 'month', -1),
  timeBuild('year', 'month'),
  timeBuild('year', 'month', -1),
]

const timeFormat = [
  date => app.time.load(date).format('HH:mm'),
  date => app.time.load(date).format('HH:mm'),
  date => app.time.load(date).format('MM-DD'),
  date => app.time.load(date).format('MM-DD'),
  date => app.time.load(date).format('MM-DD'),
  date => app.time.load(date).format('MM-DD'),
  date => app.time.load(date).format('YYYY-MM'),
  date => app.time.load(date).format('YYYY-MM'),
  date => app.time.load(date).format('YYYY-MM'),
  date => app.time.load(date).format('YYYY-MM')
]

// 统计订单
export default {
  where: reactive({
    checkout_id: 0,
    time: 0,
    time_arr: []
  }),

  time: ref([]),

  // 数据
  data: reactive({
    total: 0,
    tax: 0,
    money_tax: 0,
    profit: 0,
    count: 0,
    pay: 0
  }),

  // 列表
  list: {
    total: ref([]),
    tax: ref([]),
    req: ref([]),
    profit: ref([]),
    count: ref([])
  },

  // 支付
  pay: ref({}),

  // 获取
  async get() {
    const checkout_id = this.where.checkout_id
    const time = timeData[this.where.time]
    const format = timeFormat[this.where.time]
    this.where.time_arr = [time[0][0], time[time.length - 1][1]]
    this.getPay()

    this.time.value = []
    this.data.total = 0
    this.data.tax = 0
    this.data.money_tax = 0
    this.data.profit = 0
    this.data.count = 0
    this.list.total.value = []
    this.list.tax.value = []
    this.list.req.value = []
    this.list.profit.value = []
    this.list.count.value = []

    for (let i = 0; i < time.length; i++) {
      const res = await total({ checkout_id, time: time[i] })
      this.time.value.push(format(time[i][0]))
      this.data.total = math.add(this.data.total, Number(res.total ?? 0))
      this.data.tax = math.add(this.data.tax, math.add(Number(res.tax_money ?? 0), Number(res.req_money ?? 0)))
      this.data.money_tax = math.sub(this.data.total, this.data.tax)
      this.data.profit = math.add(this.data.profit, Number(res.profit_money ?? 0))
      this.data.count = math.add(this.data.count, Number(res.count ?? 0))

      this.list.total.value.push(Number(res.total ?? 0))
      this.list.tax.value.push(Number(res.tax_money ?? 0))
      this.list.req.value.push(Number(res.req_money ?? 0))
      this.list.profit.value.push(Number(res.profit_money ?? 0))
      this.list.count.value.push(Number(res.count ?? 0))

      await this.delay(100)
    }

  },

  async getPay() {
    const data = await totalGroup({ 
      checkout_id: this.where.checkout_id, 
      time: this.where.time_arr
    })
    const filter = {}
    this.data.pay = 0
    this.pay.value = data.map((item, index) => {
      let name = item.pay_name
      filter[item.pay_name] = filter[item.pay_name] ?? 0
      filter[item.pay_name]++
      // 出现次数大于1
      if(filter[item.pay_name] > 1) {
        name += filter[item.pay_name].toString()
      }
      // 累计
      this.data.pay = math.add(this.data.pay, item.money)
      
      return {
        name: name,
        value: item.money,
        selected: !index,
        groupId: item.pay_id
      }
    })
  },

  // 间隔
  async delay(time) {
    return new Promise((ok) => {
      setTimeout(() => {
        ok()
      }, time)
    })
  },

  // 按天查询当前条件
  async day(time) {
    const where = { 
      checkout_id: this.where.checkout_id, 
      time: [ time[0].unix(), time[1].unix() ]
    }

    // 统计
    const data = await total(where)
    // 附加
    data.time = app.time.date(time[0].unix())
    data.tax = math.add(Number(data.tax_money ?? 0), Number(data.req_money ?? 0))
    data.money_tax = math.sub(data.total, data.tax);

    // 支付方式
    (await totalGroup(where)).forEach(item => {
      data['pay-' + item.pay_id] = item.money
    })

    return data
  },

  // 打印
  print() {
    const checkout = checkoutModel.find(this.where.checkout_id)
    const user = accountModel.getUser()
    const time = this.where.time_arr

    const print = [{
        "a": "AlignCenter" 
      }, {
        "a": "Size",
        "p": [1]
      }, {
        "a": "Text",
        "p": [checkout ? checkout.name : 'RESUMEN DE VENTAS']
      }, {
        "a": "Size",
        "p": [0]
      }, {
        "a": "Line"
      }, {
        "a": "Text",
        "p": ["CIF: " + user.tax]
      }, {
        "a": "Text",
        "p": ["Fecha: " + app.time.date(time[0]) +  '-' + app.time.date(time[1])]
      }, {
        "a": "Separator",
        "p": ["-"]
      }, {
        "a": "AlignLeft" 
      }
    ]
    
    this.pay.value.forEach(item => {
      print.push({
        "a": "Table",
        "p": [[item.name, app.money(item.value, false)], [26, -22]]
      })
    })

    print.push({
      "a": "Table",
      "p": [['Subtotal', app.money(this.data.money_tax, false)], [26, -22]]
    }, {
      "a": "Table",
      "p": [['Impuesto', app.money(this.data.tax, false)], [26, -22]]
    }, {
      "a": "Separator",
      "p": ["-"]
    }, {
      "a": "Bold"
    }, {
      "a": "Size",
      "p": [1]
    }, {
      "a": "Table",
      "p": [['TOTAL', app.money(this.data.total, false)], [12, -12]]
    }, {
      "a": "Line"
    })
    
    printerModel.printSmall(print)
  }
}